var express = require('express');
var router = express.Router();
const bcrypt = require('bcryptjs');
const SECRET = 'adasdfasdf'
const jwt = require('jsonwebtoken');
const { SuccessModel, ErrorModel } = require('../model/responseModel');
const {
    getBlogsList,
    createNewBlog,
    createUser,
    findUsername,
    findUserId,
    getBlogsListPage,
    editBlog,
    deleteBlog
} = require('../controllers/blog');
/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});
const auth = async(req, res, next) => {
        const raw = String(req.headers.authorization || '').split(' ').pop()
            // console.log(token)
        const { id } = jwt.verify(raw, SECRET)
            // console.log(id)
        const userPromise = findUserId(id);
        userPromise.then(UserData => {
                // console.log(UserData)
                req.user = UserData
                next()
            })
            // console.log(req.user)


    }
    // router.get('/indexx', function(req, res, next) {
    //     var sql = 'select * from blogs'
    //     db.query(sql, function(err, rows) {
    //         if (err) {
    //             console.log(err)
    //         } else {
    //             // res.send(rows)
    //             res.status(200).send(rows);
    //         }
    //     });
    // });
    //获取博客数据
router.get('/indexx', auth, function(req, res, next) {
    // console.log(req.query.author)
    const author = req.query.author || '';
    const keyword = req.query.keyword || '';
    const listDataPromise = getBlogsList(author, keyword);
    return listDataPromise.then((listData) => {
        {
            count = listData.length;
            console.log(listData.length)
            let page = req.query.page || 1
            var pagesize = 5;
            var start = (page - 1) * pagesize;
            // var sql = 'select * from blogs limit 9,4'
            const listPagePromise = getBlogsListPage(start, pagesize);
            listPagePromise.then((listPageData) => {
                // console.log(listPageData)
                res.send({ bloglist: listPageData, count: count, pagesize: pagesize });
            })



        }

        // return (listData);
        // res.send(new SuccessModel(listData))
        // console.log(typeof(listDataPromise))
    });
});
//获取用户对应博客分页数据
router.get('/index', auth, function(req, res, next) {

    console.log(req.user)
    const listDataPromise = getBlogsList(author, keyword);
    return listDataPromise.then((listData) => {
        // return (listData);
        console.log(listData)
        res.send(new SuccessModel(listData))
            // console.log(typeof(listDataPromise))
    });
});

//新增博客路由
router.post('/article/create', auth, function(req, res, next) {
    const blogData = req.body;
    // console.log(req.user.user[0].username)
    const author = req.user.user[0].username;
    blogData.author = author;
    console.log(blogData)
    const newBlogDataPromise = createNewBlog(blogData);

});

//编辑博客路由
router.post('/article/edit', auth, function(req, res, next) {
    const blogData = req.body;
    // blogData.author = author;
    // blogData.id = ;
    console.log(blogData)
    const editBlogDataPromise = editBlog(blogData);

});
//删除博客路由
router.post('/article/delete', auth, function(req, res, next) {
    const id = req.query.id;
    // blogData.author = author;
    // blogData.id = ;
    const delBlogDataPromise = deleteBlog(id);

});
//博客编辑详情路由
router.get('/detail', function(req, res) {
    const id = req.query.id;
    console.log(req.query.id)
    const blogDetailDataPromise = getBlogsList('', id);
    return blogDetailDataPromise.then((listData) => {
        // return (listData);
        // console.log(listData)
        res.send(new SuccessModel(listData))
            // console.log(typeof(listDataPromise))
    });
    // console.log(typeof idd, )
    // res.send(rows)
});
//注册用户路由
router.post('/register', function(req, res) {
    const author = req.body.username;
    const pass = req.body.password;
    const salt = bcrypt.genSaltSync(10);
    const password = bcrypt.hashSync(pass, salt);
    const userDataPromise = createUser(author, password);
    return userDataPromise.then(newUserData => {
        res.send(new SuccessModel(newUserData))
    })

});
//登录路由生成token
router.post('/login', function(req, res) {
    const { username, password } = req.body
        // 1.根据用户名找用户
    const userLoginPromise = findUsername(username);
    return userLoginPromise.then(UserData => {
        console.log(UserData)

        // res.send(new SuccessModel(newUserData))
        if (!UserData.user[0]) {
            console.log('422')
            return res.status(422).send({
                message: '用户不存在'
            })
        }
        console.log(UserData.user[0].password)
            //比较密码
        const isPasswordValid = bcrypt.compareSync(req.body.password, UserData.user[0].password)
        if (!isPasswordValid) {

            console.log('密码错误')
            return res.status(422).send({
                message: '密码错误'
            })
        }
        //生成token
        const token = jwt.sign({
                id: (UserData.user[0].id),
            }, SECRET)
            // res.send({ rows, token })
        res.send(token)
    })

})
router.get('/api/profie', function(req, res) {
    // res.send(JSON.stringify(req.user))
    console.log(req.user)

})

// router.get('/test', function(req, res, next) {

//     const token = String(req.headers.authorization || '').split(' ').pop()
//     tokenData = jwt.verify(token)
//     console.log(token)
//     var sqlcount = 'select count(*) as kk from blogs'
//     var count;
//     var bloglist;
//     db.query(sqlcount, function(err, rows) {
//         if (err) {
//             console.log(err)
//         } else {
//             count = JSON.parse(JSON.stringify(rows))[0].kk;
//             // res.status(200).send(rows);
//             let page = req.query.page || 1
//             var pagesize = 5;
//             var start = (page - 1) * pagesize;
//             // var sql = 'select * from blogs limit 9,4'
//             var sql = 'select * from blogs limit ' + start + ' , ' + pagesize;
//             db.query(sql, function(err, rows) {
//                 if (err) {
//                     console.log(err)
//                 } else {
//                     // res.status(200).send(rows);
//                     res.send({ bloglist: rows, count: count });

//                 }
//             });

//         }
//     });





// });

// router.get('/indexx/detail', function(req, res) {
//     const idd = req.query.id;

//     const sql = `select * from blogs where id='${idd}'`;
//     console.log(typeof idd, )
//     db.query(sql, function(err, rows) {
//         if (err) {
//             console.log(err)
//         } else {
//             res.send(rows)
//         }
//     });
// });

// router.post('/indexx/delete', function(req, res, next) {
//     const id = req.query.id;
//     const sql = `delete from blogs where id=${id} `;
//     db.query(sql, function(err, rows) {
//         if (err) {
//             console.log(err)
//         } else {
//             console.log(rows)
//                 // res.send(rows)
//             res.status(200).send(rows);
//         }
//     });

// });

// router.post('/indexx/edit', function(req, res, next) {
//     const blogData = req.body;

//     const title = blogData.title;
//     const id = blogData.id;
//     const content = blogData.content;
//     console.log(id)
//     const sql = `update blogs set title='${title}', content='${content}' where id=${id};`;
//     db.query(sql, function(err, rows) {
//         if (err) {
//             console.log(err)
//         } else {
//             console.log(rows)
//                 // res.send(rows)
//             res.status(200).send(rows);
//         }
//     });

// });

router.post('/create', auth, function(req, res) {
    const blogData = req.body;
    const title = blogData.title;
    const content = blogData.content;
    const author = req.user.user[0].username;
    blogData.author = author
    const newBlogPromise = createNewBlog(blogData);
    // console.log(blogData)
    // newBlogPromise.then(blogData => {
    //     // console.log(UserData)
    //     // req.user = blogData
    // })


});


module.exports = router;